/*
 * Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "los_schedlimit_pri.h"

typedef struct TaskSchedLimitInfor {
    UINT64      allRuntime;
    UINT64      endTime;
} TaskSchedLimitInfor;

static TaskSchedLimitInfor g_taskSchedLimitInfors[LOSCFG_BASE_CORE_TSK_LIMIT];

ProcSchedLimiter g_procSchedLimiter;

STATIC UINT64 CycleToUs(UINT64 cycles)
{
    return (cycles *OS_NS_PER_CYCLE) / OS_SYS_NS_PER_US;
}

STATIC UINT64 UsToCycle(UINT64 us)
{
    return us * (OS_SYS_CLOCK / CORE_US_PER_SECOND);
}

void SchedLimiterCpuCtrl(LosTaskCB *runTask, UINT64 currTime)
{
    UINT32 intSave;
    ProcSchedLimiter *procSchedLimiter = NULL;
    UINT64 currTimeInUs;
    UINT64 startTimeInUs;
    UINT64 irqUseTimeInUs;
    UINT64 incTimeInUs;
    UINT64 waitTimeInUs;

    currTimeInUs = CycleToUs(currTime);
    startTimeInUs = CycleToUs(runTask->startTime);
    irqUseTimeInUs = CycleToUs(runTask->irqUsedTime);
    incTimeInUs = currTimeInUs - startTimeInUs - irqUseTimeInUs;
    if (g_isInitProcLimiterSet == FALSE) {
        return;
    }
    if (LOS_SpinHeld(&g_plimitsSpin)) {
        return;
    }
    PLIMITS_LOCK(intSave);
    ProcLimiterSet *procLimiterSet = g_procLimiterSetArray[runTask->processID];
    if ((procLimiterSet == NULL) || (procLimiterSet->procLimiterList[PROCESS_LIMITER_ID_SCHED] == NULL)) {
        PLIMITS_UNLOCK_NOSCHED(intSave);
        return;
    }
    if (procLimiterSet == &g_procLimiterSet) {
        PLIMITS_UNLOCK_NOSCHED(intSave);
        return;
    }
    procSchedLimiter = procLimiterSet->procLimiterList[PROCESS_LIMITER_ID_SCHED]->private;
    if (procSchedLimiter == NULL) {
        PLIMITS_UNLOCK_NOSCHED(intSave);
        return;
    }
    if ((procSchedLimiter->period < PLIMITS_MIN_PERIOD_IN_US) || (procSchedLimiter->quota < PLIMITS_MIN_QUOTA_IN_US)) {
        PLIMITS_UNLOCK_NOSCHED(intSave);
        return;
    }

    if (procSchedLimiter->endTime == 0) {
        procSchedLimiter->endTime = currTimeInUs;
    }
    if (currTimeInUs > procSchedLimiter->endTime) {
        procSchedLimiter->startTime = procSchedLimiter->endTime;
        procSchedLimiter->endTime = procSchedLimiter->startTime + procSchedLimiter->period;
        procSchedLimiter->allRuntime = procSchedLimiter->overrunTime;
        procSchedLimiter->overrunTime = 0;
    }
    if (g_taskSchedLimitInfors[runTask->taskID].endTime < procSchedLimiter->endTime) {
        g_taskSchedLimitInfors[runTask->taskID].endTime = procSchedLimiter->endTime;
        g_taskSchedLimitInfors[runTask->taskID].allRuntime = 0;
    }
    procSchedLimiter->allRuntime += incTimeInUs;
    g_taskSchedLimitInfors[runTask->taskID].allRuntime += incTimeInUs;

    if (procSchedLimiter->allRuntime >= procSchedLimiter->quota) {
        runTask->taskStatus |= OS_TASK_STATUS_PEND_TIME | OS_TASK_STATUS_PENDING;
        UINT64 overrunTime = procSchedLimiter->allRuntime - procSchedLimiter->quota;
        waitTimeInUs = procSchedLimiter->endTime - currTimeInUs + overrunTime;
        runTask->waitTime = UsToCycle(waitTimeInUs);
        procSchedLimiter->overrunTime = overrunTime;
    }
    PLIMITS_UNLOCK_NOSCHED(intSave);
}

void *SchedLimiterAlloc(void)
{
    ProcSchedLimiter *plimiter = (ProcSchedLimiter *)LOS_KernelMalloc(sizeof(ProcSchedLimiter));
    if (plimiter == NULL) {
        return NULL;
    }
    memset_s(plimiter, sizeof(ProcSchedLimiter), 0, sizeof(ProcSchedLimiter));
    return (void *)plimiter;
}

void SchedLimiterInit(void)
{
    return;
}

void SchedLimiterCopy(UINT8 *dest, UINT8 *src)
{
    ProcSchedLimiter *plimiterDest = (ProcSchedLimiter *)dest;
    ProcSchedLimiter *plimiterSrc = (ProcSchedLimiter *)src;
    plimiterDest->period = plimiterSrc->period;
    plimiterDest->quota = plimiterSrc->quota;
    return;
}

void SchedLimiterShowStat(struct SeqBuf *seqBuf, void *data)
{
    UINT32 intSave;

    PLIMITS_LOCK(intSave);
    (void)LosBufPrintf(seqBuf, "taskId  allRuntime    endTime\n");

    for (int taskId = 0; taskId < LOSCFG_BASE_CORE_TSK_LIMIT; ++taskId) {
        if ((g_taskSchedLimitInfors[taskId].allRuntime != 0) || (g_taskSchedLimitInfors[taskId].endTime != 0)) {
            (void)LosBufPrintf(seqBuf, "%10lu   %llu   %llu\n", taskId,
                    g_taskSchedLimitInfors[taskId].allRuntime, g_taskSchedLimitInfors[taskId].endTime);
        }
    }
    PLIMITS_UNLOCK_NOSCHED(intSave);
    return;
}
